package net.kesumu.yushabu;


import java.net.URI;
import java.net.URLEncoder;
import java.util.Locale;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.general.security.HashFunctionService;
import net.kesumu.yushabu.storage.FriendDbOperator;
import net.kesumu.yushabu.testing.ConnectionService;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;
import net.kesumu.yushabuserver.entity.User;

import org.json.JSONException;
import org.json.JSONObject;







import com.codebutler.android_websockets.WebSocketClient;
import com.umeng.message.PushAgent;

import net.kesumu.yushabu.R;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    private EasyStorage mEasyStorage;
    
    public final static String TYPE_LOGIN = "type_login",
                               TYPE_REGISTER = "type_register";
    
    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] {
            "foo@example.com:hello", "bar@example.com:world" };

    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;
    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;
    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    
    String type;
    boolean resultReceived = false;
    String result;
    String mMyId;
    String mMyEmail;
    String mMyName;
    String mYuYuChatId;
    String mMySignature;
    String mMyGender;
    String mMyArea;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_login));
      //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));

        
        
        // Set up the login form.
        mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(mEmail);
        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    public boolean onEditorAction(TextView textView, int id,
                            KeyEvent keyEvent) {
                        if (id == R.id.login || id == EditorInfo.IME_NULL) {
                            attemptLogin();
                            return true;
                        }
                        return false;
                    }
                });
        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
        findViewById(R.id.sign_in_button).setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View view) {
                        attemptLogin();
                    }
                });
        myOnCreate();
    }
    
    /**
     * extend the onCreate() function
     */
    void myOnCreate() {
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mEmail = mEasyStorage.getString("email");
        mPassword = mEasyStorage.getString("password");
        //temptly set the value for quick login
        mEmailView.setText(mEmail);
        mEmailView.requestFocus(MODE_APPEND);
        mPasswordView.setText(mPassword);
        if(mPassword != null && mPassword.length()!=0) {
            mPasswordView.requestFocus(MODE_APPEND);
        }
        Intent i = getIntent();
        type = i.getStringExtra("type");
        if(type.equalsIgnoreCase(TYPE_LOGIN)) {
            ((Button)findViewById(R.id.sign_in_button)).setText(getString(R.string.btn_login));
            mPasswordView.setImeActionLabel(getResources().getString(R.string.btn_login), 
                                                                        KeyEvent.KEYCODE_ENTER);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.btn_login));
            
        }else if(type.equalsIgnoreCase(TYPE_REGISTER)){
            ((Button)findViewById(R.id.sign_in_button)).setText(R.string.btn_register);
            mPasswordView.setImeActionLabel(getResources().getString(R.string.btn_register), 
                                                                        KeyEvent.KEYCODE_ENTER);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.btn_register));
        }
        
        
        
        mPasswordView.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    attemptLogin();
                    handled = true;
                }
                return handled;
            }
        });
        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//        if (id == R.id.action_forgot_password) {
//            forceLogin();
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }
    
    void forceLogin(){
        showToast(JSONUtil.FLAG_LOGIN + " " + result + "!");
        Intent loginSuccessIntent = new Intent(LoginActivity.this, MainActivity.class);
        loginSuccessIntent.putExtra("loginResult", "success");
        startActivity(loginSuccessIntent);
        if(client != null & client.isConnected()){
            client.disconnect();
        }
        finish();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }
    


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);
        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            //waiting
//            findViewById(R.id.waiting).setVisibility(View.VISIBLE);
//            findViewById(R.id.login_form).setVisibility(View.INVISIBLE);
            showProgress(true);
//            mAuthTask = new UserLoginTask();
//            mAuthTask.execute((Void) null);
            myAttemptLogin();
        }
    }
    
    void myAttemptLogin() {
        if(!client.isConnected()) {
            client.connect();
        }
        //sign in
        if(type.equalsIgnoreCase(TYPE_LOGIN)) {
            sendRequest(jsonUtil.getLoginJSON(mEmail, HashFunctionService.hashSHA256(mPassword)));
        }else if(type.equalsIgnoreCase(TYPE_REGISTER)){
            sendRequest(jsonUtil.getRegisterJSON(mEmail, HashFunctionService.hashSHA256(mPassword)));
        }
        mEasyStorage.putString("email", mEmail);
        mEasyStorage.putString("password", mPassword);
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE
                                    : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE
                                    : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            // Simulate network access.
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }
            try {
                //wait 2 seconds to see whether succeed
                for(int i=0;i<2;i++) {
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                return false;
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success || (result != null && result.equalsIgnoreCase("success"))) {
                successfulLogin();
            } else {
                showToast(JSONUtil.FLAG_LOGIN + " " + result + "!");
                resultReceived = false;
                mPasswordView
                        .setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
    
    void successfulLogin(){
        mEasyStorage.putString("myId", mMyId);
        mEasyStorage.putString("myEmail", mMyEmail);
        mEasyStorage.putString("myName", mMyName);
        mEasyStorage.putString("mYuYuChatId", mYuYuChatId);
        mEasyStorage.putString("mMySignature", mMySignature);
        mEasyStorage.putString("mMyGender", mMyGender);
        mEasyStorage.putString("mMyArea", mMyArea);
        
        final User mySelf = new User(Integer.parseInt(mMyId), mMyName, "", "", "", "");
        
        Intent intent = new Intent(WelcomeActivity.BROADCAST_TYPE_FINISH);
        sendBroadcast(intent);
        
        Intent loginSuccessIntent = new Intent(LoginActivity.this, MainActivity.class);
        loginSuccessIntent.putExtra("loginResult", result);
        loginSuccessIntent.putExtra("myId", mMyId);
        loginSuccessIntent.putExtra("myEmail", mMyEmail);
        loginSuccessIntent.putExtra("myName", mMyName);
        loginSuccessIntent.putExtra("mYuYuChatId", mYuYuChatId);
        startActivity(loginSuccessIntent);
        finish();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
         
        if(client != null & client.isConnected()){
            client.disconnect();
        }
    }
    
    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {
                
            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    private void sendRequest(String message) {
        if (client != null && client.isConnected()) {
            client.send(message);
        }
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_REGISTER)) {
                result = jObj.getString("result");
                showToast(result);
                
                if(result != null && result.equalsIgnoreCase("success")) {
                    mMyId = jObj.getString("userId");
                    mMyEmail = jObj.getString("email");
                    mMyName = jObj.getString("name");
                    mYuYuChatId = jObj.getString("yuyuChatId");
                    mMySignature = jObj.getString("signature");
                    mMyGender = jObj.getString("gender");
                    mMyArea = jObj.getString("area");
                    successfulLogin();
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showProgress(false);
                            mEmailView.setError(getString(R.string.error_email_used));
                            mEmailView.requestFocus();
                       }
                    });
                }
            } else if (flag.equalsIgnoreCase(JSONUtil.FLAG_LOGIN)) {
                result = jObj.getString("result");
                showToast(result);
                
                if(result != null && result.equalsIgnoreCase("success")) {
                    mMyId = jObj.getString("userId");
                    mMyEmail = jObj.getString("email");
                    mMyName = jObj.getString("name");
                    mYuYuChatId = jObj.getString("yuyuChatId");
                    mMySignature = jObj.getString("signature");
                    mMyGender = jObj.getString("gender");
                    mMyArea = jObj.getString("area");
                    successfulLogin();
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showProgress(false);
                            mPasswordView
                            .setError(getString(R.string.error_incorrect_password));
                            mPasswordView.requestFocus();
                       }
                    });
                }
            }
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }
}
